import Foundation
import UIKit
import SnapKit
import Alamofire

class ViewController: UIViewController{
    // 定义模型（Codable 协议）
    struct User: Codable {
        let id: Int
        let name: String
        let email: String
    }
    // 定义请求参数结构体
    struct Post: Codable {
        let title: String
        let body: String
        let userId: Int
    }

    // 定义响应数据结构体
    struct PostResponse: Codable {
        let id: Int
        let title: String
        let body: String
        let userId: Int
    }

    override func viewDidLoad(){
        fetchUserData(userId: 67)
//        createPost()
//        createPostWithEncodable()
    }
    func fetchUserData(userId: Int) {
        let url = "http://127.0.0.1:4523/m1/6699763-6409492-default"
        let api = "/api/user/\(userId)"
        
        AF.request(url+api, method: .get)
            .validate(statusCode: 200..<300) // 确保 HTTP 状态码是 2xx
            .responseDecodable(of: User.self) { response in
                switch response.result {
                case .success(let user):
                    print("用户数据: \(user)")
                case .failure(let error):
                    print("错误: \(error.localizedDescription)")
                }
            }
    }
    func createPost() {
        // 1. 设置API端点
        let url = "https://jsonplaceholder.typicode.com/posts"
        
        // 2. 准备请求参数
        let parameters: [String: Any] = [
            "title": "foo",
            "body": "bar",
            "userId": 1
        ]
        
        // 3. 发起POST请求
        AF.request(url,
                   method: .post,
                   parameters: parameters,
                   encoding: JSONEncoding.default)
            .validate(statusCode: 200..<300)  // 验证状态码
            .responseDecodable(of: PostResponse.self) { response in
                switch response.result {
                case .success(let postResponse):
                    print("创建成功: \(postResponse)")
                case .failure(let error):
                    print("请求失败: \(error.localizedDescription)")
                }
            }
    }
    func createPostWithEncodable() {
        let url = "https://jsonplaceholder.typicode.com/posts"
        
        // 1. 创建可编码的参数对象
        let newPost = Post(title: "Swift POST",
                           body: "使用Alamofire发送POST请求",
                           userId: 1)
        
        // 2. 设置请求头
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]
        
        // 3. 发起请求
        AF.request(url,
                   method: .post,
                   parameters: newPost,
                   encoder: JSONParameterEncoder.default,
                   headers: headers)
            .validate()
            .response { response in
                // 处理原始响应
                switch response.result {
                case .success(let data):
                    if let data = data {
                        print("响应数据: \(String(data: data, encoding: .utf8) ?? "")")
                    }
                case .failure(let error):
                    print("错误: \(error.localizedDescription)")
                }
            }
    }

}
